package net.mujiwulian.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.mujiwulian.entity.User;
import net.mujiwulian.service.UserService;
import net.mujiwulian.service.UserSimpleService;
import net.mujiwulian.view.UserSimple;
import net.mujiwulian.vo.PageQuery;
import net.mujiwulian.vo.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * @Author: silence
 * @Description:
 * @Date:Create：in 2019/12/28 13:17
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final UserService userService;
    private final UserSimpleService userSimpleService;

    public UserController(UserSimpleService userSimpleService, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userSimpleService = userSimpleService;
        this.userService = userService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @GetMapping("/info")
    public Result<UserSimple> info(UserSimple userSimple) {
        return new Result<>(Result.CodeStatus.OK, "获取用户信息", userSimpleService.getById(userSimple.getId()).setPassword(null));
    }

    @GetMapping("/infoDetails")
    public Result<User> infoDetails(UserSimple userSimple) {
        User user = userService.getById(userSimple.getId());
        user.setPassword(null);
        return new Result<>(Result.CodeStatus.OK, "获取用户详细信息", user);
    }

    @PostMapping("/updateInfo")
    public Result<Void> updateInfo(@RequestBody User user) {
        user.setCreateTime(null).setRole(null).setPassword(null).setUsername(null);
        return new Result<>("修改信息", userService.updateById(user));
    }

    @PostMapping("/updatePwd")
    public Result<Void> updatePwd(Integer id, String oldPwd, String newPwd) {
        if (id == null || StringUtils.isEmpty(oldPwd) || StringUtils.isEmpty(newPwd)) {
            return new Result<>(Result.CodeStatus.FAIL, "参数错误");
        }
        UserSimple userSimple = userSimpleService.getById(id);
        if (!bCryptPasswordEncoder.matches(oldPwd, userSimple.getPassword())) {
            return new Result<>(Result.CodeStatus.FAIL, "密码验证失败");
        }
        return new Result<>("修改密码", userService.updateById(new User(id, bCryptPasswordEncoder.encode(newPwd))));
    }

    @PostMapping("/reset")
    @PreAuthorize("hasRole('1')")
    public Result<Void> reset(Integer id) {
        return new Result<>("重置密码", userService.updateById(new User(id, bCryptPasswordEncoder.encode("123456"))));
    }

    @PostMapping("/select")
    public Result<IPage<User>> get(@RequestBody PageQuery<User> pageQuery) {
        LambdaQueryWrapper<User> lq = Wrappers.lambdaQuery();
        lq.select(User.class, i -> !"password".equals(i.getColumn()));
        lq.and(StringUtils.isNotEmpty(pageQuery.getKeywords()), i -> i.like(User::getPhone, pageQuery.getKeywords()).or().like(User::getNickname, pageQuery.getKeywords()));
        return new Result<>(Result.CodeStatus.OK, "获取用户信息", userService.page(pageQuery.getPageCondition(), lq));
    }

    @PostMapping("/delete")
    @PreAuthorize("hasRole('1') or hasRole('0')")
    public Result<Void> delete(Integer id) {
        if (id == 1) {
            return new Result<>(Result.CodeStatus.FAIL, "不能删除超级管理员账户");
        }
        return new Result<>("删除账号", userService.removeById(id));
    }

    @PostMapping("/insert")
    public Result<Void> add(@RequestBody User user) {
        if (!userService.list(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername())).isEmpty()) {
            return new Result<>(Result.CodeStatus.FAIL, "账号已存在");
        }
        user.setPassword(bCryptPasswordEncoder.encode("123456"));
        user.setRole(2);
        user.setCreateTime(LocalDateTime.now());
        return new Result<>("添加用户", userService.save(user));
    }


}
